package com.atguigu.java4;

import org.junit.Test;

import java.util.*;

/**
 * @author: 王丹
 * @create: 2021-09-01 10:30
 **/
public class OptionalDemo {

    public List<User> getList() {
        List<User> users = new ArrayList<>();
        User user = new User("Tom", 22, "Street #1");
        users.add(user);
        users.add(new User("Micohael", 33, "Street #2"));
        users.add(new User("Lioly", 25, "Street #3"));
        return users;
    }

    @Test
    public void testOptional() {
        List<User> users = getList();
        User user = users.get(0);
        //判断是否为空
        Optional<User> optional = Optional.of(user);
        System.out.println("optional.isPresent() = " + optional.isPresent());
        //不确定是否为空：ofNullable中的值可以为空也可以不为空
        User user1 = null;
        Optional<User> user11 = Optional.ofNullable(user1);
        System.out.println("user11 = " + user11);
        //数据为null时给默认值
        User user2 = Optional.ofNullable(user1).orElse(user);
        System.out.println("user2 = " + user2);
        //为null时抛出指定异常
        //System.out.println("Optional.ofNullable(user1).orElseThrow(() -> new IllegalArgumentException(\"数据不能为空!\")) = " + Optional.ofNullable(user1).orElseThrow(() -> new IllegalArgumentException("数据不能为空!")));
        //对其中某个属性进行处理
        users.stream().map(t -> t.getName()).forEach(System.out::println);
        //将名字以'O'拆分并遍历
        users.stream().flatMap(x -> Arrays.stream(x.getName().split("o"))).forEach(x -> System.out.println("flatMap:" + x));
        //获取名字长度最长的名字
        System.out.println(users.stream().map(User::getName).max(Comparator.comparing(String::length)));
        //根据年龄进行排序
        users.stream().sorted(Comparator.comparing(User::getAge).reversed()).forEach(System.out::println);
        //查询年龄最大的人
        Optional<User> max = users.stream().max(Comparator.comparing(User::getAge));
        System.out.println("max.get() = " + max.get());

    }

    public String getDefaultValue() {  //远程方法调用
        System.out.println("我被调用了!");
        return "我是默认值";
    }

    /**
     * 结论
     * 无论optional是否有值，orElse都会被执行
     * 只有optional为空时，orElseGet才会被执行
     * https://blog.csdn.net/bin8632/article/details/103621649
     */
    @Test
    public void testSupplier() {
        String s = "null";
        Optional<String> opt = Optional.ofNullable(s);
        String x = opt.orElse(getDefaultValue());
        System.out.println("x = " + x);
        System.out.println("---以上为orElse调用,以下为orElseGet调用---");
        String y = opt.orElseGet(() -> getDefaultValue());
        System.out.println("y = " + y);
    }

}
